package com.glory.hikvisionmobile.customView;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.util.AttributeSet;
import android.util.Log;
import android.webkit.DownloadListener;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

/**
 * *****************************
 *
 * @Anthor yazhou
 * @Email 1184545990@qq.com
 * @Time 2020/3/11 18:53
 * @DESC *****************************
 */
public class HikWebView extends WebView {

    public HikWebView(Context context) {
        super(context);
        init();
    }

    public HikWebView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public HikWebView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    public HikWebView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        init();
    }

    public HikWebView(Context context, AttributeSet attrs, int defStyleAttr, boolean privateBrowsing) {
        super(context, attrs, defStyleAttr, privateBrowsing);
        init();
    }

    /**
     * 初始化
     */
    public void init(){
        initSetting();
        initWebViewClient();
        initWebChromeClient();

//        setDownloadListener(new DownloadListener() {
//            @Override
//            public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
//                Intent i = new Intent(Intent.ACTION_VIEW);
//                i.setData(Uri.parse(url));
//                getContext().startActivity(i);
//            }
//        });

        setHorizontalScrollBarEnabled(false);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            //setWebContentsDebuggingEnabled(true);
        }
    }

    /**
     * 初始化settings
     */
    public void initSetting(){
        WebSettings settings = getSettings();

        String ua = settings.getUserAgentString();

        //settings.setTextSize(WebSettings.TextSize.NORMAL);
        //settings.setDefaultFontSize(35);

        //如果访问的页面中要与Javascript交互，则webview必须设置支持Javascript
        settings.setJavaScriptEnabled(true);

        //支持插件
        //settings.setPluginsEnabled(true);

        //设置自适应屏幕，两者合用
        settings.setUseWideViewPort(true); //将图片调整到适合webview的大小
        settings.setLoadWithOverviewMode(true); // 缩放至屏幕的大小

        //缩放操作
        settings.setSupportZoom(true); //支持缩放，默认为true。是下面那个的前提。
        settings.setBuiltInZoomControls(true); //设置内置的缩放控件。若为false，则该WebView不可缩放
        settings.setDisplayZoomControls(true); //隐藏原生的缩放控件

        //其他细节操作
        settings.setCacheMode(WebSettings.LOAD_DEFAULT); //关闭webview中缓存
        settings.setAppCacheEnabled(true);
//        settings.setAppCachePath(SDCardUtils.getDiskCacheDir());
        settings.setAllowFileAccess(true); //设置可以访问文件
        settings.setJavaScriptCanOpenWindowsAutomatically(true); //支持通过JS打开新窗口
        settings.setLoadsImagesAutomatically(true); //支持自动加载图片
        settings.setDefaultTextEncodingName("utf-8");//设置编码格式

        /*settings.setLoadWithOverviewMode(true);
        settings.setSafeBrowsingEnabled(true);
        settings.setSupportMultipleWindows(true);*/
        settings.setSaveFormData(true);

        //启用数据库    
//        settings.setDatabaseEnabled(true);
        //设置定位的数据库路径    
//        String dir = this.getContext().getDir("database", Context.MODE_PRIVATE).getPath();
//        settings.setGeolocationDatabasePath(dir);
        //启用地理定位  
        settings.setGeolocationEnabled(true);
        //开启DomStorage缓存  
        settings.setDomStorageEnabled(true);

        if (Build.VERSION.SDK_INT>15) {
            settings.setAllowUniversalAccessFromFileURLs(true);
        }
        // 如果不使用该句代码，在点击超链地址后，会跳出程序，而弹出浏览器访问网页。
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {//使用https访问 加载图片
            settings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }

        //settings.setBlockNetworkImage(false);
    }

    /**
     * 初始化WebViewClient
     */
    private void initWebViewClient(){
        setWebViewClient(new WebViewClient(){
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                return super.shouldOverrideUrlLoading(view, request);
            }

            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                super.onReceivedError(view, errorCode, description, failingUrl);
                if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
                    return;
                }
            }

            // 在Android6以上的机器上，网页中的任意一个资源获取不到（比如字体），网页就很可能显示自定义的错误界面
            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    if (request.isForMainFrame()) { // 解决方案

                    }
                }else {

                }
                super.onReceivedError(view, request, error);
            }
        });
    }

    /**
     * 初始化WebChromeClient
     */
    private void initWebChromeClient(){
        WebChromeClient sWebChromeClient = new WebChromeClient(){
            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
            }

            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);

            }
        };

        setWebChromeClient(sWebChromeClient);
    }
}
